﻿using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.BuildEngine;
using System.Runtime.InteropServices;
using Microsoft.Tools.CodeRunner.Tasks;

namespace Microsoft.Tools.CodeRunner.Tasks.UnitTest
{
    [TestClass]
    public class MSBuildTests
    {
        private static TestContext testContext;
        private static BuildPropertyGroup globalProperties = new BuildPropertyGroup();

        [ClassInitialize]
        public static void Initialize(TestContext testContext)
        {
            MSBuildTests.testContext = testContext;
        }

        [DeploymentItem(@"UnitTest\TestSource\Example.proj")]
        [DeploymentItem(@"UnitTest\TestSource\HelloWorld.csr")]
        [TestMethod]
        public void TestCsrTaskInMSBuild()
        {
            string projectFile = @"Example.proj";
            string logFile = @"Build.log";

            RunBuild(projectFile, logFile, "Build");
        }
        
        private void RunBuild(string projectFile, string logFile, string target)
        {
            bool result = false;
            Engine engine = new Engine();

            try
            {
                FileLogger fileLogger = new FileLogger();

                fileLogger.Parameters = String.Format("logfile={0}", logFile);
                fileLogger.Verbosity = LoggerVerbosity.Diagnostic;

                TraceLogger traceLogger = new TraceLogger();

                traceLogger.Verbosity = LoggerVerbosity.Normal;

                engine.RegisterLogger(fileLogger);
                engine.RegisterLogger(traceLogger);

                result = engine.BuildProjectFile(projectFile, new string[] { target }, globalProperties);
            }
            finally
            {
                engine.UnregisterAllLoggers();
            }

            Assert.IsTrue(result,
                String.Format("Build of project '{0}', target '{1}' failed.  See {2} for more details.",
                    projectFile, target, logFile));
        }
    }
}
